package view;

import java.rmi.RemoteException;

import javax.swing.JFrame;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.JTableHeader;
import javax.swing.table.TableColumn;

import server.FirewallSession;

import server.FirewallException;
import server.GlobalLog;
import server.Log;


/**
 * Class is responsible for the logger table building.
 */
public class LoggerGlobalTable extends JTable
{
	/**
	 * 
	 */
	
	/**
	 * server controller
	 */
	public FirewallSession UI;
	
	/* Current logger table */
	public static LoggerGlobalTable currentLoggerGlobalTable = null;
	
	/* Column names */
	private final static String columnNames[] = 
		{"Time", "Event" };
	
	/* Table data */
	public static GlobalLog[] loggerGlobalData = null;
		
	/**
	 * C'tor
	 * Create table with scroll.
	 * Size is defined hard coded.
	 */
	public LoggerGlobalTable(FirewallSession ui)
	{
		super(Settings.windowDepth, columnNames.length);
		this.UI = ui;
		currentLoggerGlobalTable = this;
	    setAutoResizeMode (JTable.AUTO_RESIZE_OFF);
		build();
	}
	
	/**
	 * Create table header.
	 */
	public JTableHeader getLoggerGlobalTableHeader()
	{
		TableColumn column = null;
		for (int i = 0; i < columnNames.length; i++)
		{
		    column = getColumnModel().getColumn(i);
		    column.setHeaderValue(columnNames[i]);
		}
		
		return getTableHeader();	
	}
	
	/**
	 * Cancel cell editing for user.
	 */
	public boolean isCellEditable(int row, int column) 
	{
		return false;
	}

	/**
	 * Fill the table.
	 */
	public void build()
	{

		
		getLoggerGlobalData();
		
		if(loggerGlobalData != null)
		{
			/* Add new rows if it's needed */
			int diff = loggerGlobalData.length - getModel().getRowCount();
			
			/* Clear the previous data */
			((DefaultTableModel)getModel()).setRowCount(0);
			if(diff > 0)
			{
				((DefaultTableModel)getModel()).setRowCount(1+ loggerGlobalData.length);
			}
			else
			{
				((DefaultTableModel)getModel()).setRowCount(1+Settings.DEFAULT_LOGGER_WINDOW_DEPTH);
			}
			
			for(int i = 0; i < loggerGlobalData.length; i++)
			{
				int j = 0;
				this.setValueAt(loggerGlobalData[i].time,      i, j++);
				this.setValueAt(loggerGlobalData[i].event,     i, j++);
			}			
		}
		else /*if(loggerData != null)*/
		{
			/* Clear the previous data */			
			((DefaultTableModel)getModel()).setRowCount(0);
			((DefaultTableModel)getModel()).setRowCount(Settings.DEFAULT_LOGGER_WINDOW_DEPTH);
		}
	}
	
	/**
	 * Take the data from UI.
	 */
	private void getLoggerGlobalData()
	{
		try {
			LoggerGlobalTable.loggerGlobalData = UI.getGlobalLogs(Settings.historyDepth);			
		} catch (RemoteException e) {
			ErrorFrame.AddError("Failed to get log data:" + e.getMessage(), new JFrame());
		} catch (FirewallException e) {
			ErrorFrame.AddError("Failed to get log data:"  + e.getMessage(), new JFrame());
		}
	}
}
